package com.xlh.Utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.SocketException;
import org.apache.commons.net.telnet.TelnetClient;

import com.xlh.interf.TelnetHandler;

public class TelnetHelper implements Runnable {

	private String host;
	private int port;
	//鏉堟挸鍙嗘潏鎾冲毉缂傛挸鍟块崠锟�
	private PrintStream out = null;
	private InputStream in = null;
	// 
	private TelnetClient telnet = null;

	// telnet閸楀繗顔匳T100 VT52
	// VT220 VTNT
	// ANSI
	//private String TelType = "VT220";
	private String TelType = "VT220";

	// 婢舵牠鍎撮柦鈺佺摍
	public TelnetHandler recvCompleteHandler = null;


	public TelnetHelper(String host, int port) {
	
		this.host = host;
		this.port = port;
	

	}
	
	/**
	 * 閸欐垿锟戒焦瀵氭禒锟�
	 * 閺傝纭堕崝鐔诲厴鐠囧瓨妲戦敍锟� 
	 * 閸掓稑缂撻敍锟�016-9-23 by fang   
	 * 娣囶喗鏁奸敍姘）閺堬拷 by 娣囶喗鏁奸懓锟� 
	 * 娣囶喗鏁奸崘鍛啇閿涳拷  
	 * @閸欏倹鏆熼敍锟�@param cmd      
	 * @return void     
	 * @throws
	 */
	public void Send(String cmd){
		this.out.println(cmd);
		this.out.flush();
	}
	
	
	@SuppressWarnings("deprecation")
	public void Close(){
			try {
				this.telnet.disconnect();
				Thread.currentThread().destroy();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
	}
	
	
	//瀵拷婵娲冮崥顒佹箛閸旓紕顏崣鎴炴降閻ㄥ嫭绉烽幁锟�

	@Override
	public void run() {


			if ( recvCompleteHandler==null ){
				throw new ExceptionInInitializerError("recvCompleteHandler not set!!");

			}
		
		try {
			telnet = new TelnetClient(this.TelType);

			telnet.connect(this.host, this.port);
			// in out 
			out = new PrintStream(telnet.getOutputStream());
			this.in = telnet.getInputStream();

			if (out == null || in == null) {
			
				throw new ExceptionInInitializerError("out with in void!!");
				
				//return;
			}

		
			StringBuffer sb = new StringBuffer();
			String s = "";

			@SuppressWarnings("unused")
			char firstCharKey = '\0';
			
			char ch = (char) in.read();
			while (true) {

			
				sb.append(ch);

			
				byte[] temp = sb.toString().getBytes("iso8859-1");
				s = new String(temp, "utf-8");
				if (s.indexOf("$!$")>0){
				//if (firstCharKey == '\r' && ch == '\n') {
					// recvCompleteHandler();
					
					if (this.recvCompleteHandler==null){
						throw new ExceptionInInitializerError("recvCompleteHandler not set!");
					}
					
					this.recvCompleteHandler.OnRecvComplete(s);
					sb.delete(0, sb.length());
					s = "";
				}

				firstCharKey = ch;
				ch = (char)in.read();

			}
		} catch (SocketException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}
}
